package paper.crawler;

import java.util.LinkedList;
import java.util.ListIterator;

import paper.crawler.LinkEvent;

/* 
 * Maintains a group of links to be visited. The links are stored in a
 * priority list, odered on the quality of the link. The quality is
 * predicted by the linkscraper.
 */
public class LinkSet {
    private LinkedList<LinkEvent> schedule = new LinkedList<LinkEvent>();

    /*
     * Method to add a triple 'Event' to the linkset. This is a triple
     * containing the URL, the limit on the hopCount and the quality of the
     * link.
     */
    public synchronized void addEvent(LinkEvent e) {    // fixme - can be made more efficient...
        for(ListIterator<LinkEvent> i = schedule.listIterator(); i.hasNext();){
            LinkEvent x = i.next();
            if (x.quality < e.quality) {
                i.add(e);
                return;
            }
        }
        schedule.add(e);
    }

    public void addEvent(String url, int hopCount, double quality) {
        addEvent(new LinkEvent(url, hopCount, quality));
    }

    /*
     * Checks whether this linkset is empty. Don't retrieve links from an
     * empty set, it gives you an exception of some sort me thinks. Maybe a
     * null pointer...
     */
    public boolean isEmpty() {
        return schedule.isEmpty();
    }

    /*
     * Get a triple URL, quality, hopCount from the schedule. It is removed
     * from the schedule.
     */
    public synchronized LinkEvent getEvent() {
        return schedule.removeFirst();
    }
}
